package controller;

import model.Goods;
import model.Order;
import service.GoodsService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 加入购物车
 */
@WebServlet(name = "GoodsBuy",value = "/goods_buy")
public class GoodsBuyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        GoodsService gs = new GoodsService();
        Order order = null;
        if (req.getSession().getAttribute("order") != null) {
            order = (Order) req.getSession().getAttribute("order");
        } else {
            order = new Order();
            req.getSession().setAttribute("order", order);
        }
        int id = Integer.parseInt(req.getParameter("goodsid"));
        try {
            Goods goods = gs.goods_detail(id);
            if (goods.getStock() > 0) {
                order.addGoods(goods);
                req.getSession().setAttribute("order", order);
                //获取请求来自哪里
                String referer = req.getHeader("referer");
                //返回刷新
                resp.sendRedirect(referer);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
